import { useEffect, useRef, useState } from "react";
import { Link, useLocation } from "react-router-dom";
import {
  FileImageOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  ProfileOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { Button, Flex, Layout, Menu, type MenuProps } from "antd";
import ReactIcon from "@/assets/svg/react.svg?react";
import { useTheme } from "@/components/theme-provider";
import { ROUTE_PATHS } from "@/constants/common";
import { setCollapsed, useSelector, useSettingsStore } from "@/stores";

// 递归函数，找到匹配的菜单项
const findSelectedKeys = (items: MenuProps["items"], pathname: string, path: string[] = []) => {
  const selectedKeys: string[] = [];
  let openKeys: string[] = [];

  const travel = (items: MenuProps["items"], pathname: string, path: string[]) => {
    for (const item of items!) {
      const itemKey = item!.key as string;

      // 精确匹配
      if (itemKey === pathname) {
        selectedKeys.push(itemKey);
        openKeys = [...path];
        return;
      }

      // 如果当前路径是菜单项的子路径，也激活该菜单项
      if (pathname.startsWith(itemKey + "/")) {
        selectedKeys.push(itemKey);
        openKeys = [...path];
        return;
      }

      if ((item as any).children) {
        path.push(itemKey);
        travel((item as any).children, pathname, path);
        path.pop();
      }
    }
  };

  travel(items, pathname, path);
  return { selectedKeys, openKeys };
};

const items: MenuProps["items"] = [
  {
    icon: <UserOutlined />,
    label: <Link to={ROUTE_PATHS.user}>用户管理</Link>,
    key: ROUTE_PATHS.user,
  },
  {
    icon: <FileImageOutlined />,
    label: <Link to={ROUTE_PATHS.material}>素材管理</Link>,
    key: ROUTE_PATHS.material,
  },
  {
    icon: <ProfileOutlined />,
    label: <Link to={ROUTE_PATHS.order}>商单管理</Link>,
    key: ROUTE_PATHS.order,
  },
];

export default function SiderBar() {
  const location = useLocation();

  const firstRenderRef = useRef(true);

  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);

  const { collapsed } = useSettingsStore(useSelector(["collapsed"]));

  const { isDarkMode } = useTheme();

  useEffect(() => {
    if (location.pathname === "/") return;

    const { selectedKeys, openKeys } = findSelectedKeys(items, location.pathname);
    setSelectedKeys(selectedKeys);
    // 首次渲染时，设置默认值
    if (firstRenderRef.current) {
      setOpenKeys(openKeys);
    }
    // 将首次渲染标记设置为false
    firstRenderRef.current = false;
  }, [location.pathname]);

  return (
    <Layout.Sider
      trigger={null}
      collapsible
      collapsed={collapsed}
      theme={isDarkMode ? "dark" : "light"}
      className="h-screen overflow-auto !sticky top-0 left-0 start-0"
    >
      <Flex>
        <Flex flex={1} justify="center" align="center">
          <Link
            className="font-bold text-xl hover:text-current h-12 flex justify-center items-center text-nowrap"
            to="/"
          >
            <Flex align="center" gap={4} className="flex-1 justify-center">
              <ReactIcon className="size-6" />
              {collapsed ? null : <span className="text-gradient-ripple">Koc Agent</span>}
            </Flex>
          </Link>
        </Flex>
        <Flex justify="end" align="center">
          <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
          />
        </Flex>
      </Flex>
      <Menu
        theme={isDarkMode ? "dark" : "light"}
        mode="inline"
        items={items}
        selectedKeys={selectedKeys}
        // onSelect={({ selectedKeys }) => setSelectedKeys(selectedKeys)}
        openKeys={openKeys}
        onOpenChange={(openKeys) => setOpenKeys(openKeys)}
        className="!border-e-0"
      />
    </Layout.Sider>
  );
}
